<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
panic/recover 2
</h1>
<p></p>
<div id="question" class="tmd-base">
<p></p>
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

func main() {
	defer func() {
		println(recover().(int))
	}()
	defer func() {
		defer func() {
			recover()
		}()
		defer recover()
		panic(3)
	}()
	defer func() {
		defer func() {
			defer func() {
				recover()
			}()
		}()
		defer recover()
		panic(2)
	}()
	panic(1)
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">1</label></li>
<li><label for="choiceB">2</label></li>
<li><label for="choiceC">3</label></li>
<li><label for="choiceD">&lt;nil&gt;</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 2
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/xawck_2YOWz">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Except the two <code class="tmd-code-span">recover</code> calls at line 9 and 5, the other ones are all no-op.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The <code class="tmd-code-span">recover</code> calls at line 9 recovers the panic <code class="tmd-code-span">3</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The <code class="tmd-code-span">recover</code> calls at line 5 recovers the panic <code class="tmd-code-span">2</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The the panic <code class="tmd-code-span">1</code> is never recovered, but it is suppressed by the panic <code class="tmd-code-span">2</code>.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
Please read <a href="https://go101.org/article/panic-and-recover-more.html">Explain Panic/Recover Mechanism in Detail</a> for details.
</div>
<p></p>
</div>
<p></p>
</div>
